import { objToUri, page, routeJump, getLayoutTabbarPageUrl, getSwitchLayoutTabbarPageUrl, goLogin, isNumber, isString,empty } from '@/common/utils';
import type { RouteJumpPath } from '@/common/utils';
import { toast, toastApp } from '@/common/utils/toast';
import type { UniAppConfig, ModalParams, JumpParams, GoLogin, LayoutGoTo } from './type';
import { WHITE_ROUTE } from '@/env';

const appGoLogin: GoLogin = function (this: UniAppConfig['globalProperties'], { isShowModal = true, goToUrl = '', wxJumpType = '1' } = {}) {
	// #ifdef MP-WEIXIN||MP-ALIPAY
	if (isShowModal) {
		this.$showModal({
			title: this.$t('common.您还未登录'),
			// content: '您还未登录',
			confirmText: this.$t('common.去登录'),
			cancelColor: '#333333',
			success: (res: { confirm: boolean; }) => {
				if (res.confirm) {
					// #ifdef MP-WEIXIN
					routeJump('/pages/public/account/wxLogin', 'navigateTo');
					// #endif
					// #ifdef MP-ALIPAY
					routeJump('/pages/public/account/aliLogin', 'navigateTo');
					// #endif
				}
			}
		});
		return;
	}

	// #endif
	goLogin({
		goToUrl,
		wxJumpType
	});
};

const jumpCheck = function (this: UniAppConfig['globalProperties'], url: RouteJumpPath, options = {}) {
	let goToUrl = Object.keys(options).length > 0 ? `${url}?${objToUri(options)}` : url;
	const checkUrl = url.split('?')[0]
	if (
		!this.$pinia.state.value?.user?.isLogin &&
		!WHITE_ROUTE.some((item) => {
			if (isString(item)) {
				return item === checkUrl;
			}
			return item.test(checkUrl);
		})
	) {
		appGoLogin.apply(this, [
			{
				goToUrl
			}
		]);
		return '';
	}

	return goToUrl;
};

export default {
	init({ globalProperties }: UniAppConfig) {
		/**
		 * 此方法在APP下使用原生消息提示
		 * @method $toastApp
		 * @for UinAppUtil
		 * @param {msg} 提示内容
		 */
		globalProperties.$toastApp = toastApp;

		globalProperties.$toast = toast;
		/**
		 * 弹窗提示框
		 * @method $showModal
		 * @for UinAppUtils
		 * @param  params
		 * 与uni.showModal参数一致
		 */
		globalProperties.$showModal = function (params: ModalParams) {
			if (!params.title) {
				params.title = this.$t('common.提示');
			}
			(params.cancelColor = params.cancelColor || '#4D4D4D'), (params.confirmColor = params.confirmColor || getApp().globalData?.cssPrimaryColor || this.$cssPrimaryColor);
			uni.showModal(params);
		};
		globalProperties.$goLogin = appGoLogin;
		uni.$_goLogin = () => {
			globalProperties.$goLogin();
		};
		/**
		 * 页面跳转
		 */
		globalProperties.$goTo = function (...args: JumpParams) {
			// console.log('不需要登录', hasLogin);
			routeJump(jumpCheck.apply(this, [args[0],args[1]]), 'navigateTo', args[2], args[3]);
		};
		let layoutGoTo: LayoutGoTo;
		layoutGoTo = function (this: UniAppConfig['globalProperties'], link, pageTitle) {
			if(empty(link))return 
			// pageTitle为页面标题，可不传
			if (link?.pageType == 2) {
				// 跳转的页面是tabbar页
				const index =  this.$pinia.state.value.init.tabbarData.findIndex(item => item.link.pageUrl && item.link.pageUrl === link.pageUrl);
				if (index > -1) {
					// 在tabbar页或普通页点击了跳转tabbar页的链接均需修改tabbarPageUrl的值
					this.$pinia.state.value.init.tabbarPageIndex = index;
					// #ifdef APP
					const tabbarPageUrl = getSwitchLayoutTabbarPageUrl(link.pageUrl);
					this.$switchTab(tabbarPageUrl);
					// #endif
					// #ifndef APP
					if (page() !== '/pages/tabbar/index') {
						// 在普通页点击了跳转tabbar页的链接需先跳转到tabbar
						this.$switchTab('/pages/tabbar/index');
					}
					// #endif
				} else {
					const tabbarPageUrl = getLayoutTabbarPageUrl(link.pageUrl);
					if (tabbarPageUrl) {
						this.$goTo(tabbarPageUrl);
					} else {
						this.$toastApp(this.$t('common.没有对应页面'));
					}
				}
			} else {
				if (link.isOther) {
					if(link.linkUrl.includes('app/#/pages/store/join/index')||link.linkUrl.includes('valenceVertex')||link.linkUrl.includes('storeApp')){
						if(!this.$pinia.state.value?.user?.isLogin){
							this.$goLogin()
							return 
						}
						link.linkUrl+=`?token=${uni.getStorageSync('token')}&tenant=${uni.getStorageSync('tenant')}`
					}
					// #ifdef H5
					location.href = link.linkUrl;
					// #endif
					// #ifndef H5
					this.$pinia.state.value.layout.otherUrl = link.linkUrl
					let arr = link.linkUrl.split('?');
					let url = arr[0];
					this.$goTo('/pages/web', { url });
					// #endif
				} else if (link?.isMp) {
					if (link.mpType === 1) {
						// #ifdef MP-WEIXIN
						uni.navigateToMiniProgram({
							appId: link.appId,
							path: link.path
						});
						// #endif
						// #ifdef APP
						plus.share.getServices(
							(res) => {
								let sweixin = res.find((i) => i.id === 'weixin');
								if (sweixin) {
									// 分享跳转到微信小程序
									sweixin.launchMiniProgram({
										id: link.appId, //微信小程序原生id
										path: link.path, //打开小程序的页面路径，不传默认跳转首页
										type: 0 //微信小程序版本类型，可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
									});
								} else {
									uni.showToast({
										title: '请安装微信',

										icon: 'none'
									});
								}
							},
							(err) => {
								console.log(err); // 获取分享服务列表失败
							}
						);

						// #endif
					}
				}else if (link?.isAppSystemApi) {
					// 调用系统api
					if (link.appSystemApiType === 1) {
						uni.scanCode({
							success: function (res) {
								if (/(http|https):\/\/([\w.]+\/?)\S*/.test(res.result)) {
									// 如果是链接
									let arr = res.result.split('?');
									if (res.result.includes('pages/nearby/pay')) {
										this.$goTo('/pages/systemPay/nearby/pay?' + arr[1]);
									} else {
										this.$pinia.state.value.layout.otherUrl = res.result;
										this.$goTo('/pages/web', { url:arr[0] });
									}
								}else{
									this.$toastApp('error');
								}
							}
						});
					}
				} else {
					// 跳转的页面是普通页
					let url = link.linkUrl!;
					if(url === '/app/agent/manager'){
						url = '/pages/user/agent/index'
					}else if(url === '/app/promote/merchant'){
						url = '/pages/user/promote/index'
					}
					if (pageTitle) {
						if (url.indexOf('?') > -1 && pageTitle) {
							// 链接带?号，代表自身有参数
							url = `${url}&pageTitle=${pageTitle}`;
							this.$goTo(url);
						} else {
							this.$goTo(url, { pageTitle });
						}
					} else {
						this.$goTo(url);
					}
				}
			}
		};
		/**
		 * 装修组件专用页面跳转
		 */
		globalProperties.$layoutGoTo = layoutGoTo;
		/**
		 * 页面跳转-关闭当前
		 */
		globalProperties.$goRedirectTo = function (...args: JumpParams) {
			routeJump(jumpCheck.apply(this, [args[0],args[1]]), 'redirectTo', args[2], args[3]);
		};
		/**
		 * 页面跳转-关闭所有页面
		 */
		globalProperties.$goReLaunch = function (...args: JumpParams) {
			routeJump(jumpCheck.apply(this, [args[0],args[1]]), 'reLaunch', args[2], args[3]);
		};
		/**
		 * 页面跳转-自定义跳转tabbar页
		 */
		globalProperties.$switchTab = function (...args: JumpParams) {
			// #ifdef APP||MP-WEIXIN||MP-ALIPAY
			uni.switchTab({
				url: args[0]
			});
			// #endif
			// #ifndef APP||MP-WEIXIN||MP-ALIPAY
			routeJump(args[0], 'reLaunch');
			// #endif
		};

		/**
		 * 页面跳转-返回上一页
		 */
		globalProperties.$back = function (delta = 1) {
			delta = isNumber(delta) ? delta : 1;
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - (1 + delta)];
			if (!prevPage) {
				this.$switchTab('/pages/tabbar/index');
			} else {
				uni.navigateBack({
					delta
				});
			}
		};
		globalProperties.$toastAndBack = function (msg:string, delta = 1) {
			toastApp(msg);
			setTimeout(() => {
				uni.navigateBack({
					delta
				});
			}, 1000);
		};
	}
};
